<?
/**
 * is a files-proxy for internal and external files.
 * @example $file = new cachbuster($file)
 */
class FWcache
{
    var $extUrl;
    var $fileage;

    /**
     * Inits the cachbuster for a specific file
     * @param string $extUrl
     * @param string $fileage in seconds (used for unix time) optional else every 4 month
     */
    function __construct( $extUrl, $fileage = NULL ) {}
    function run()
    {
        $intUrl = $this->generateInternalUrl($this->extUrl);
        if( !file_exists($intUrl) OR ( $this->fileage < ( time() - @filemtime($intUrl) ) AND @filemtime($intUrl) > 0)  )
        {
            if($this->freezeFile($this->extUrl, $intUrl) === FALSE)
            {
                return "FALSE";
            }
        }
        return $intUrl;
    }

    function init($extUrl, $fileage = NULL)
    {
        $this->extUrl = $extUrl;
        $stnd_filage = 4 * 7*24*60*60;
        $this->fileage = ($fileage !== NULL) ? $fileage : $stnd_filage;
        return $this->run();
    }
    function generateInternalUrl($extUrl)
    {
        $c = config::getInstance();
        $parsed = parse_url($extUrl);
        $extention = preg_replace("/[^a-zA-Z0-9\s]/", "", strrchr($parsed["path"], "."));    
        return $c->get("cb_dir") . "/" . str_replace(".", "_", $parsed["host"]) . "/" . md5($extUrl) . "." . ($extention ? $extention : "data");
    }
    function freezeFile($extUrl,$intUrl)
    {
        if(!is_dir(dirname($intUrl)))
        {
            mkdir (dirname($intUrl));
        }
        $handle = @fopen($extUrl, "rb");
        if($handle)
        {
            $somecontent = stream_get_contents($handle);
            fclose($handle);

            $handle = fopen($intUrl, 'wb');
            if($handle)
            {
                if (fwrite($handle, $somecontent) === FALSE)
                {
                #echo "Cannot write to file ($intUrl)";
                    return FALSE;
                }
                #echo "Success, wrote ($somecontent) to file ($intUrl)";
                fclose($handle);
                return TRUE;
            }else
            {
            #echo "Cannot create file ($intUrl)";
                return FALSE;
            }
        }
        else
        {
        #echo "cannot open file ($extUrl)";
            return FALSE;
        }
    }
}

?>